package com.yidu.hbats.action.Attachment;
import com.yidu.hbats.model.AtsAttachment;
import com.yidu.hbats.model.AtsAttachmentEmp;
import com.yidu.hbats.model.AtsSchemeAudit;
import com.yidu.hbats.service.attachment.AtsAttachmentService;
import com.yidu.springbootdemo.permission.action.vo.TuserVo;
import com.yidu.springbootdemo.permission.domain.Tuser;
import com.yidu.springbootdemo.permission.service.TuserService;
import com.yidu.utils.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 附件表控制器
 * @author 彭乐
 * @create: 2019-12-10 18:39
 */
@Controller
@RequestMapping("/atsAttachmentController")
public class AtsAttachmentController {
    @Resource
    AtsAttachmentService atsAttachmentService;
    @Resource
    TuserService tuserService;
    @Resource
    FileTools fileTools;

    /**
     * 新增或修改附件表
     * @param session 会话对象
     * @param atsAttachment 附件表对象
     * @param empIds 人员
     * @return
     */
    @ResponseBody
    @RequestMapping("addOrUpdate")
    public Message addOrUpdate(HttpSession session, AtsAttachment atsAttachment ,String empIds){
        int count;
        Message message = new Message();
        //获取登录用户
        Tuser user = (Tuser)session.getAttribute("user");
        //获取登录用户姓名
        String name = user.getUserName();
        //设置发布人
        atsAttachment.setAttachPublisher(name);
        //设置状态为1
        atsAttachment.setIsva(1);
        //设置审核状态为20
        atsAttachment.setAuditState(20);
        //获取前台接收人员
        List<AtsAttachmentEmp> emps = getAtsAttachmentEmp(empIds);
        try {
            if (!atsAttachment.getFileOne().isEmpty()){
                String file1 = fileTools.saveFile("atsAttachment",atsAttachment.getFileOne());
                atsAttachment.setFile1(file1);
            }
            if (!atsAttachment.getFileTwo().isEmpty()){
                String file2 = fileTools.saveFile("atsAttachment",atsAttachment.getFileTwo());
                atsAttachment.setFile2(file2);
            }
            if (!atsAttachment.getFileThree().isEmpty()){
                String file3 = fileTools.saveFile("atsAttachment",atsAttachment.getFileThree());
                atsAttachment.setFile3(file3);
            }
            //根据id传入判断新增，修改
            if(StringUtils.isEmpty(atsAttachment.getAttachId())){
                //获取当前时间
                String time =new Tools().getCurDateTime();
                //设置当前时间
                atsAttachment.setAttachTime(getDate(time));
                count = atsAttachmentService.insertSelective(atsAttachment,emps);
                if(count > 0 ){
                    message.setNum(1);
                    message.setMsg("新增成功");
                }else{
                    message.setNum(2);
                    message.setMsg("新增失败");
                }
            }else{
                count = atsAttachmentService.updateByPrimaryKeySelective(atsAttachment,emps);
                if(count >0){
                    message.setNum(1);
                    message.setMsg("修改成功");
                }else{
                    message.setNum(2);
                    message.setMsg("修改失败");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return message;
    }

    /**
     * 单个逻辑删除
     * @param atsAttachment 附件对象
     * @return 删除数
     */
    @ResponseBody
    @RequestMapping("updateIsva")
    public int  updateIsva(AtsAttachment atsAttachment){
        //设置状态为0
        atsAttachment.setIsva(0);
        return  atsAttachmentService.updateByPrimaryKey(atsAttachment);
    }

    /**
     * 批量逻辑删除
     * @param attachId 主键
     * @return 删除个数
     */
    @ResponseBody
    @RequestMapping("updateIsvaAll")
    public int  updateIsvaAll(String attachId){
        //分割字符串，得到id数组
        String []attachIds=attachId.split(",");
        //接收删除
        int rows=0;
        //循环刚才分隔得出来的数组
        for(int i=0;i<attachIds.length;i++) {
            //创建附件对象
            AtsAttachment atsAttachment = new AtsAttachment();
            //设置附件id
            atsAttachment.setAttachId(Integer.valueOf(attachIds[i]));
            //修改状态为0
            atsAttachment.setIsva(0);
            //执行sql
            atsAttachmentService.updateByPrimaryKey(atsAttachment);
            //每执行一次计数变量加一
            rows++;
        }
        return  rows;
    }
    /**
     *修改审核状态
     */
    @ResponseBody
    @RequestMapping("UpdateAuditState")
    public Integer UpdateAuditState(HttpSession session,AtsAttachment atsAttachment, AtsSchemeAudit atsSchemeAudit){
        //创建工具类
        Tools tools =new Tools();
        //设置审核表外键
        atsSchemeAudit.setSaId(atsAttachment.getAttachId().toString());
        //获取当前时间
        String time=tools.getCurDateTime();
        //设置审核时间
        atsSchemeAudit.setAuTime(time);//审核时间取当前时间
        //设置备注字段
        String remark="";
        //获取通知类型
        String attachType=atsAttachment.getAttachType();
       //10 通知公告，20,公务信息，30 文件政策 ，40 学习资料
        if(attachType!=null && attachType.equals("10")){
            remark="通知公告";
        }else if(attachType!=null && attachType.equals("20")){
            remark="公务信息";
        }else if(attachType!=null && attachType.equals("30")){
            remark="文件政策";
        }else if(attachType!=null && attachType.equals("40")){
            remark="学习资料";
        }
        //设置审核备注
        atsSchemeAudit.setRemark(remark);
        //设置审核状态，附件表状态20发布对应10，25对应20,30对应21
        String auditState="";
        if(atsAttachment.getAuditState()==20){
            auditState="10";
        }else if(atsAttachment.getAuditState()==25){
            auditState="20";
        }else if(atsAttachment.getAuditState()==30){
            auditState="21";
        }
        //设置审核状态
        atsSchemeAudit.setAuditState(auditState);
        //设置审核标题
        atsSchemeAudit.setSaName(atsAttachment.getAttachName());
        //获取登录人员信息
        Tuser user = (Tuser) session.getAttribute("user");
       //设置审核人员
        atsSchemeAudit.setCreater(user.getUserName());
        //设置存在状态1
        atsSchemeAudit.setIsva(1);
       int count= atsAttachmentService.updateAuditState(atsAttachment,atsSchemeAudit);
        return count;
    }

    /**
     * 根据id查询
     * @param attachId 附件id
     * @return 根据id查询的附件对象
     */
    @ResponseBody
    @RequestMapping("findById")
    public AtsAttachment findEmpById(Integer attachId){
        return atsAttachmentService.selectByPrimaryKey(attachId);
    }

    /**
     * 查询附件表所有信息
     * @param atsAttachment 附件表对象
     * @param time 时间
     * @param pages 分页
     * @return
     */
    @ResponseBody
    @RequestMapping("selectAll")
    public Map<String,Object> selectAll(AtsAttachment atsAttachment,Time time,Pages pages){
        //创建map对象
        Map<String, Object> map = new HashMap<String, Object>();
        //设置分页总数
        pages.setTotalRows(atsAttachmentService.selectCount(atsAttachment,time));
        //查询
        List<AtsAttachment> list = atsAttachmentService.selectAll(time,pages,atsAttachment);
        // 放入 code ，0
        map.put("code",0);
        // 放入msg “”
        map.put("msg", "");
        // 放入总行数
        map.put("count",pages.getTotalRows());
        // 放入集合
        map.put("data", list);
        return map;
    }

    /**
     * 查询所有待审核数据
     * @param atsAttachment
     * @param time
     * @param pages
     * @return
     */
    @ResponseBody
    @RequestMapping("selectCheckAll")
    public Map<String,Object> selectCheckAll(AtsAttachment atsAttachment,Time time,Pages pages){

        Map<String, Object> map = new HashMap<String, Object>();
        pages.setTotalRows(atsAttachmentService.selectCheckCount(atsAttachment,time));
        List<AtsAttachment> list = atsAttachmentService.selectCheckAll(time,pages,atsAttachment);
        map.put("code",0); // 放入 code ，0
        map.put("msg", ""); // 放入msg “”
        map.put("count",pages.getTotalRows()); // 放入总行数
        map.put("data", list);
        return map;
    }

    /**
     * 查询所有审核成功的数据
     * @param atsAttachment
     * @param time
     * @param pages
     * @return
     */
    @ResponseBody
    @RequestMapping("selectLookAll")
    public Map<String,Object> selectLookAll(HttpSession session,AtsAttachment atsAttachment,Time time,Pages pages){
        Tuser user = (Tuser) session.getAttribute("user");
        String userId = user.getUserId();
        time.setCurrentTime(new Tools().getCurDate());
        Map<String, Object> map = new HashMap<String, Object>();
        pages.setTotalRows(atsAttachmentService.selectLookCount(userId,atsAttachment,time));
        List<AtsAttachment> list = atsAttachmentService.selectLookAll(userId,time,pages,atsAttachment);
        map.put("code",0); // 放入 code ，0
        map.put("msg", ""); // 放入msg “”
        map.put("count",pages.getTotalRows()); // 放入总行数
        map.put("data", list);
        return map;

    }


    /**
     * 查询所有人员
     * @return 人员信息树节点
     */
    @ResponseBody
    @RequestMapping("selEmpTree")
    public List<TreeNode> selEmpTree(){
       //创建节点对象集合
        List<TreeNode> list = new ArrayList<TreeNode>();
       //创建领导leader节点
        TreeNode leader = new TreeNode();
        //设置节点id为1
        leader.setId("1");
        //设置节点名称为领导
        leader.setTitle("领导");
        //创建领导子节点leaderChildrens集合
        List<TreeNode> leaderChildrens = new ArrayList<TreeNode>();
       //创键领导集合 1
        List<Tuser> leaderEmp = tuserService.selBycompanyNum("1");
        //循环领导集合
        for (Tuser tuser : leaderEmp) {
            //创建子节点对象
            TreeNode leaderChildren = new TreeNode();
            //设置子节点id
            leaderChildren.setId(tuser.getUserId());
            //设置子节点标题
            leaderChildren.setTitle(tuser.getCompanyName());
            //将子节点加入集合
            leaderChildrens.add(leaderChildren);
        }
        //设置子节点
        leader.setChildren(leaderChildrens);
        //将领导对象加入集合
        list.add(leader);
        //教练员 节点 coach
        TreeNode coach = new TreeNode();
        //设置教练节点id 2
        coach.setId("2");
        //设置教练节点标题
        coach.setTitle("教练员");
        //创建教练子节点集合
        List<TreeNode> coachChildrens = new ArrayList<TreeNode>();
        //创建教练人员集合
        List<Tuser> coachEmp = tuserService.selBycompanyNum("2");
        //循环教练员集合
        for (Tuser tuser : coachEmp) {
            //创建教练员coachChildren子节点对象
            TreeNode coachChildren = new TreeNode();
           //将教练员id设置为子节点id，
            coachChildren.setId(tuser.getUserId());
            //将教练员姓名设为节点标题
            coachChildren.setTitle(tuser.getCompanyName());
            //将子节点添加到集合
            coachChildrens.add(coachChildren);
        }
        //将子节点集合加入教练员节点
        coach.setChildren(coachChildrens);
        //将教练员节点加入集合
        list.add(coach);
        //创建专家节点 expert
        TreeNode expert = new TreeNode();
        //设置专家节点
        expert.setId("3");
        //设置节点标题
        expert.setTitle("专家");
        //创建专家子节点expertChildrens集合
        List<TreeNode> expertChildrens = new ArrayList<TreeNode>();
        //获取专家人员集合
        List<Tuser> expertEmp = tuserService.selBycompanyNum("3");
       //循环专家人员集合
        for (Tuser tuser : expertEmp) {
            //创建专家子节点对象
            TreeNode expertChildren = new TreeNode();
            //设置子节点id
            expertChildren.setId(tuser.getUserId());
            //设置子节点标题
            expertChildren.setTitle(tuser.getCompanyName());
            //将子节点加入集合
            expertChildrens.add(expertChildren);
        }
        //将子节点加入节点
        expert.setChildren(expertChildrens);
        //将节点加入集合
        list.add(expert);

        //运动员节点 athlete
        TreeNode athlete = new TreeNode();
        //设置节点id
        athlete.setId("4");
        //设置节点标题
        athlete.setTitle("运动员");
        //子节点 athleteChildrens
        List<TreeNode> athleteChildrens = new ArrayList<TreeNode>();
        //运动员集合
        List<Tuser> athleteEmp = tuserService.selBycompanyNum("4");
        //循环运动员集合
        for (Tuser tuser : athleteEmp) {
            //子节点
            TreeNode athleteChildren = new TreeNode();
            //子节点id
            athleteChildren.setId(tuser.getUserId());
            //子节点标题
            athleteChildren.setTitle(tuser.getCompanyName());
            //加入子节点集合
            athleteChildrens.add(athleteChildren);
        }
        //加入节点
        athlete.setChildren(athleteChildrens);
        //节点加入集合
        list.add(athlete);
        //返回集合
        return list;
    }


    /**
     * 获取接收人员
     * @param empIds
     * @return
     */
    public List<AtsAttachmentEmp> getAtsAttachmentEmp(String empIds){
     //创建附件人员表集合
    List<AtsAttachmentEmp> emps = new ArrayList<AtsAttachmentEmp>();
    //创建人员集合
    List<TuserVo> tusers =new ArrayList<TuserVo>();
    //为空查询所有人员
    if(empIds.isEmpty()){
        //集合接收所有人员信息
        tusers = tuserService.selAll();
    }else{
        //将字符串分解为数据对象
        String[] empid = empIds.split(",");
        for (String s : empid) {
            //根据id查询人员信息
            TuserVo tuser = tuserService.findByID(s);
            //将人员信息添加到集合
            tusers.add(tuser);
        }
    }
    //循环人员集合
    for (TuserVo tuser : tusers) {
      //创建附件人员对象
        AtsAttachmentEmp emp = new AtsAttachmentEmp();
       //设置名称
        emp.setUserName(tuser.getUserName());
        //设置id
        emp.setUserId(tuser.getUserId());
        //设置是否查看0
        emp.setIsLook(0);
        //将附件人员对象加入集合
        emps.add(emp);
    }
    return emps;
}
    public Date getDate(String dateString) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        Date date = null;
        try {
            date = simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
@InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }


}
